package org.bitmaps
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.MovieClip;
	import flash.utils.Dictionary;
	
	import org.bitmaps.data.BmpSourceInfo;
	import org.bitmaps.display.BmpMovieClip;
	import org.bitmaps.event.BmpEvent;
	import org.bitmaps.event.BmpEventManager;
	import org.utils.BitmapDataInfo;
	import org.utils.BitmapUtils;
	
	/**
	 * 绘制位图管理类
	 * @author anjue
	 */
	public final class BmpDrawManager
	{
		private static var _drawing:Boolean = false;
		private static var sourceList:Array = new Array();
		private static var bmpHash:Dictionary = new Dictionary();
		
		private static var cnt:uint = 0;
		private static var scnt:uint = 0;
		/**
		 * 绘制影片
		 * @param m
		 */
		public static function draw(key:String,source:*,completeFun:Function=null):void
		{
			if(bmpHash.hasOwnProperty(key))
			{
				var bmpMovie:BmpMovieClip = new BmpMovieClip();
				bmpMovie.frames = bmpHash[key];
				drawComplete(key,bmpMovie);
			}else
			{
				var bmpInfo:BmpSourceInfo = new BmpSourceInfo();
				bmpInfo.key = key;
				bmpInfo.source = source;
				bmpInfo.completeFun = completeFun;
				sourceList.push(bmpInfo);
				loop();
			}
		}
		
		private static function loop():void
		{
			if(!_drawing)
			{
				if(sourceList.length >0)
					drawSource(sourceList[0]);
			}
		}
		
		private static function drawSource(sourceInfo:BmpSourceInfo):void
		{
			_drawing = true;
			var bmpList:Vector.<BitmapDataInfo> = new Vector.<BitmapDataInfo>;
			if(sourceInfo.source is MovieClip)
			{
				var _m:MovieClip = sourceInfo.source as MovieClip;
				var i:uint = 0;
				for(i;i<_m.totalFrames;i++)
				{
					_m.gotoAndStop(i);
					var _bmp:BitmapDataInfo = BitmapUtils.drawBitmapData(_m,true);
					bmpList.push(_bmp);
				}
			}
			
			var bmpMovie:BmpMovieClip = new BmpMovieClip();
			bmpMovie.frames = bmpList;
			drawComplete(sourceInfo.key,bmpMovie);
			sourceList.splice(sourceList.indexOf(sourceInfo),1);
			_drawing = false;
			bmpHash[sourceInfo.key] = bmpList;
			
			loop();
		}
		
		private static function drawComplete(key:String,bmpMovie:*):void
		{
			var eve:BmpEvent = new BmpEvent(BmpEvent.COMPLETE);
			eve.key = key;
			eve.data = bmpMovie;
			BmpEventManager.dispatchEvent(eve);
		}
	}
}